package com.sc.session;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.security.support.MyResponse;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.Assert;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * @author sc
 * Created on  2018/1/19
 */
@Slf4j
public class AbstractSessionStategy {
    private String destinationUrl;
    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    @Setter
    private boolean createNewSession = true;
    private ObjectMapper objectMapper = new ObjectMapper();

    public AbstractSessionStategy(String invalidUrl){
        Assert.isTrue(UrlUtils.isValidRedirectUrl(invalidUrl),"url格式错误");
        this.destinationUrl = invalidUrl;
    }

    protected void onSessionInvalid(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if(createNewSession){
            request.getSession();
        }
        String sourceUrl = request.getRequestURI();
        String targetUrl;
        if(StringUtils.endsWithIgnoreCase(sourceUrl,".html")){
            targetUrl = destinationUrl+".html";
            log.info("session失效,跳转到"+targetUrl);
            redirectStrategy.sendRedirect(request,response,targetUrl);
        }else {
            String message = "session失效";
            if(isConcurrency()){
                message = message+"不允许并发登录";
            }
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(new MyResponse(message)));
        }
    }

    protected boolean isConcurrency() {
        return false;
    }


}
